# -*- coding: utf-8 -*-
"""
数据库工具 - PostgreSQL连接（只读模式）

@author: AI Assistant
"""
import psycopg2
from loguru import logger
from config import WATER_DATABASE_URL


def get_database_connection():
    """获取数据库连接（只读）
    
    Returns:
        数据库连接对象
    """
    try:
        conn = psycopg2.connect(WATER_DATABASE_URL)
        return conn
    except Exception as e:
        logger.error(f"数据库连接失败: {e}")
        raise


def get_postgres_data():
    """获取PostgreSQL连接（兼容主项目接口）
    
    Returns:
        数据库连接对象
    """
    return get_database_connection()


def execute_query(sql: str, params: tuple = None):
    """执行查询并返回结果（只读）
    
    Args:
        sql: SQL 查询语句
        params: 查询参数
        
    Returns:
        查询结果和列名
    """
    try:
        conn = get_database_connection()
        cursor = conn.cursor()
        
        if params:
            cursor.execute(sql, params)
        else:
            cursor.execute(sql)
        
        results = cursor.fetchall()
        columns = [desc[0] for desc in cursor.description]
        
        cursor.close()
        conn.close()
        
        return results, columns
        
    except Exception as e:
        logger.error(f"执行查询失败: {str(e)}")
        if 'conn' in locals():
            conn.close()
        raise


if __name__ == "__main__":
    # 测试数据库连接
    try:
        conn = get_database_connection()
        logger.info("✅ 数据库连接成功")
        conn.close()
    except Exception as e:
        logger.error(f"❌ 数据库连接失败: {e}")

